<template>
  <div>
    <!-- 表格体 -->
    <a-table :columns="columns" :data-source="formData" :loading="loading" :pagination="pagination" @change="handleTableChange">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'name'">
          <a>
            {{ record.name }}
          </a>
        </template>
        <template v-else-if="column.key === 'type'">
          <span>
            <a-tag v-if="record.type === 0" color="geekblue">事假</a-tag>
            <a-tag v-else-if="record.type === 1" color="yellow">产假</a-tag>
            <a-tag v-else-if="record.type === 2" color="red">病假</a-tag>
          </span>
        </template>
        <template v-else-if="column.key === 'reason'">
          <span>{{ formatEllipsis(record.reason) }}</span>
        </template>
        <template v-else-if="column.key === 'status'">
          <span>
            <a-tag v-if="record.status == 0" color="geekblue">待审核</a-tag>
            <a-tag v-else-if="record.status == 1" color="yellow">审核中</a-tag>
            <a-tag v-else-if="record.status == 2" color="green">已同意</a-tag>
            <a-tag v-else-if="record.status == 3" color="red">已拒绝</a-tag>
            <a-tag v-else-if="record.status == 4" color="black">已撤销</a-tag>
          </span>
        </template>
        <template v-else-if="column.key === 'action'">
          <span>
            <a-button class="btn" v-if="props.formT == '0'" :disabled="isCanCancel(record.startTime, record.status)" danger @click="cancelApply(record)">撤销</a-button>
            <a-button class="btn" v-if="props.formT == '1' || props.formT == '0'" @click="showDetail(record)">详情</a-button>
            <a-button class="btn" v-if="props.formT == '2'" @click="showApprove(record)">审核</a-button>
          </span>
        </template>
      </template>
    </a-table>
    <!-- 详情弹窗 -->
    <a-modal v-model:visible="visible" style="top: 10px" width="1000px" title="请假信息" @ok="handleOk" okText=" " cancelText=" ">
      <a-alert v-if="recordDetail.status == 4" message="提醒" description="这条请假记录已撤销" type="warning" show-icon />
      <a-steps v-else :current="recordDetail.status + 1">
        <a-step>
          <!-- <span slot="title">Finished</span> -->
          <template #title>上传</template>
        </a-step>
        <a-step title="领导审核" />
        <a-step title="人事审核" />

        <a-steps title="通过" />
      </a-steps>
      <br />
      <a-descriptions bordered>
        <a-descriptions-item label="编号">{{ recordDetail.id }}</a-descriptions-item>
        <a-descriptions-item label="姓名">{{ recordDetail.userName }}</a-descriptions-item>
        <a-descriptions-item label="类型">{{ leaveType[+recordDetail.type] }}</a-descriptions-item>
        <a-descriptions-item label="起始时间">{{ recordDetail.startTime }}</a-descriptions-item>
        <a-descriptions-item label="结束时间" :span="2">{{ recordDetail.endTime }}</a-descriptions-item>
        <a-descriptions-item label="发起时间" :span="3">{{ recordDetail.createTime }}</a-descriptions-item>
        <a-descriptions-item label="请假原因" :span="3"> {{ recordDetail.reason }}</a-descriptions-item>
        <a-descriptions-item label="领导审批人" :span="1"> {{ auditInfoStep1.auditor }}</a-descriptions-item>
        <a-descriptions-item label="领导审批结果" :span="1"> {{ approveType[auditInfoStep1.status] }}</a-descriptions-item>
        <a-descriptions-item label="领导审批时间" :span="3"> {{ auditInfoStep1.auditTime }}</a-descriptions-item>
        <a-descriptions-item v-if="auditInfoStep1.refuseReason" label="领导审批拒绝理由" :span="3"> {{ auditInfoStep1.refuseReason }}</a-descriptions-item>
        <a-descriptions-item label="人事审批人" :span="1"> {{ auditInfoStep2.auditor }}</a-descriptions-item>
        <a-descriptions-item label="人事审批结果" :span="1"> {{ approveType[auditInfoStep2.status] }}</a-descriptions-item>
        <a-descriptions-item label="人事审批时间" :span="3"> {{ auditInfoStep2.auditTime }}</a-descriptions-item>
        <a-descriptions-item v-if="auditInfoStep2.refuseReason" label="人事审批拒绝理由" :span="3"> {{ auditInfoStep2.refuseReason }}</a-descriptions-item>

        <!-- <a-descriptions-item v-if="props.formT != 2" label="拒绝原因" :span="3"> {{ recordDetail.refuseReason }}</a-descriptions-item> -->
      </a-descriptions>
      <br />
      <a-form v-if="props.formT == 2">
        <a-form-item label="拒绝理由" name="reason">
          <a-textarea v-model:value="refuseReason" :rows="4" placeholder="请输入内容" />
        </a-form-item>
      </a-form>
      <div class="btn-groups" v-if="props.formT == 2">
        <a-button type="primary" class="btn" @click="agree(recordDetail.id)" ghost>同意请假</a-button>
        <a-button type="primary" danger @click="disagree(recordDetail.id)" ghost>拒绝请假</a-button>
      </div>
    </a-modal>
  </div>
</template>

<script>
import { SmileOutlined, DownOutlined } from '@ant-design/icons-vue'
import { reactive, toRefs, ref, defineComponent, onMounted, defineExpose, nextTick } from 'vue'
import { List, Action } from '@/service'
import { result, convertToTimestamp } from '@/utils/tools'
import formType from '@/utils/FormType'
import { useStore } from 'vuex'
import { message } from 'ant-design-vue'
export default {
  props: {
    formT: {
      type: Number,
      required: true,
    },
    permission: {
      type: Number,
      required: true,
    },
    queryInfo: {
      type: String,
      required: false,
    },
  },
  setup(props) {
    // 分页器
    const pagination = reactive({
      page: 1,
      size: 1,
      current: 1,
      total: 0,
    })
    const store = useStore()
    const myId = store.state.myUserId
    // const role = ref(store.state.role.role);
    // console.log(role.value);
    const formData = ref([])
    // console.log(props)
    // console.log(formType)
    const columns = [...formType[props.formT]]
    // 获取审批人信息
    //
    const auditInfoStep1 = ref({})
    const auditInfoStep2 = ref({})
    const getAuditProcedures = async (id) => {
      const res = await List.getAuditProcedures(id)
      result(res).success(({ data }) => {
        // console.log(data);
        auditInfoStep1.value = { ...data[0] }
        auditInfoStep2.value = { ...data[1] }
        // console.log(auditInfoStep1.value)
        // console.log(auditInfoStep2.value)
      })
    }
    // 获取自己的请假列表
    const getMyLeaveForms = async () => {
      // 因获取不到后台总条数，暂时用100代替
      const res = await List.getMyLeaveForms(pagination.current, 100, myId)
      result(res).success(({ data }) => {
        // console.log(data)
        pagination.total = data.total
        // pagination.current = data.current
        formData.value = [...data.records]
        // console.log(formData.value)
        console.log('返回数据总条数：' + pagination.total)
      })
    }
    // 获取所有人的请假列表
    const getAllLeaveForms = async () => {
      // 因获取不到后台总条数，暂时用100代替
      // console.log(props.queryInfo.type, props.queryInfo.status);
      const res = await List.getAllLeaveForms(pagination.current, 100, myId, props.queryInfo.userName, props.queryInfo.type, props.queryInfo.status)
      result(res).success(({ data }) => {
        // console.log(data)
        pagination.total = data.total
        pagination.current = data.current
        formData.value = [...data.records]
        // console.log(formData.value)
        console.log(formData.value)
        console.log('返回数据总条数：' + pagination.total)
      })
    }
    const getAllUsersLeaveForms = async () => {
      // 因获取不到后台总条数，暂时用100代替
      // console.log(props.queryInfo.type, props.queryInfo.status);
      const res = await List.getAllUsersLeaveForms(pagination.current, 100, myId, props.queryInfo.userName, props.queryInfo.type, props.queryInfo.status)
      result(res).success(({ data }) => {
        // console.log(data)
        pagination.total = data.total
        pagination.current = data.current
        formData.value = [...data.records]
        // console.log(formData.value)
        console.log(formData.value)
        console.log('返回数据总条数：' + pagination.total)
      })
    }
    // 合并我的记录以及其他人记录
    // const getAllLeaveForms = () => {
    //   Promise.all([List.getMyLeaveForms(pagination.current, 100, myId), List.getAllLeaveForms(pagination.current, 100, myId, props.queryInfo)]).then((resList) => {
    //     pagination.total = resList[0].data.data.total + resList[1].data.data.total
    //     formData.value = [...resList[0].data.data.records,...resList[1].data.data.records]
    //     // console.log(resList[0].data.data);
    //   }
    //   )
    // }
    // 暴露方法
    defineExpose({
      getMyLeaveForms,
      getAllLeaveForms,
      getAllUsersLeaveForms,
    })
    function handleTableChange(e) {
      pagination.page = e.page
      pagination.current = e.current
      pagination.total = e.total
      pagination.size = e.size
      // getMyLeaveForms()
    }
    onMounted(() => {
      switch (props.permission) {
        case '1': {
          getMyLeaveForms()
          break
        }
        case '2': {
          getAllLeaveForms()
          break
        }
        case '3': {
          getAllUsersLeaveForms()
          break
        }
      }
    })
    // 取消申请
    const cancelApply = async (record) => {
      const res = await Action.deleteLeaveForm(record.id, myId)
      result(res).success(({ data }) => {
        message.success('撤销成功！')
        nextTick(() => {
          getMyLeaveForms()
        })
      })
    }
    // 确定是否可以申请撤销
    const isCanCancel = (startTime, status) => {
      // console.log(status);
      const flag1 = +new Date() - convertToTimestamp(startTime) > 0 ? true : false
      const flag2 = status == 4 ? true : false
      const flag3 = status < 1 ? false : true
      return flag1 || flag3 || flag2
    }
    // 获取record detail
    const recordDetail = ref({})
    // 请假类型数组
    const leaveType = ref(['事假', '产假', '病假'])
    // 审核类型数组
    const approveType = ref(['待审核', '审核中', '已同意', '已拒绝', '已撤销'])
    // 详情modal弹窗相关
    const visible = ref(false)
    const showDetail = (record) => {
      recordDetail.value = Object.assign({}, record)
      getAuditProcedures(record.id)
      showModal()
    }
    const showModal = () => {
      visible.value = true
    }
    const handleOk = (e) => {
      console.log(e)
      visible.value = false
    }
    // 审核相关
    const refuseReason = ref('')
    const showApprove = (record) => {
      recordDetail.value = Object.assign({}, record)
      getAuditProcedures(record.id)
      showModal()
    }
    // 同意
    const agree = async (id) => {
      const res = await Action.auditPass(id, myId)
      result(res).success(({ data }) => {
        message.success('已同意该请假申请')
        visible.value = false
        getAllLeaveForms()
      })
    }

    const disagree = async (id) => {
      if (!refuseReason.value.trim()) {
        message.warn('拒绝理由不能为空')
        return
      }
      const res = await Action.auditRefuse(id, myId, refuseReason.value)
      result(res).success(({ data }) => {
        message.success('已驳回该请假申请')
        visible.value = false
        refuseReason.value = ''
        getAllLeaveForms()
      })
    }
    const formatEllipsis = (str = '', limitLen = 40) => {
      let len = 0,
        reg = /[\x00-\xff]/, //半角字符的正则匹配
        strs = str.split(''),
        inx = strs.findIndex((s) => {
          len += reg.test(s) ? 1 : 2
          if (len > limitLen) return true
        })
      return inx === -1 ? str : str.substr(0, inx) + '...'
    }
    return {
      pagination,
      columns,
      formData,
      cancelApply,
      handleTableChange,
      getMyLeaveForms,
      isCanCancel,
      props,
      showDetail,
      visible,
      handleOk,
      recordDetail,
      leaveType,
      getAllLeaveForms,
      showApprove,
      refuseReason,
      disagree,
      getAllUsersLeaveForms,
      auditInfoStep1,
      auditInfoStep2,
      agree,
      approveType,
      formatEllipsis,
    }
  },
}
</script>

<style lang="scss" scoped>
.btn {
  margin-right: 10px;
}
.btn-groups {
  padding: 5px;
}
</style>
